import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import { message } from "antd";
import { clearAuthData, getToken, request } from "@/utils/request";
import { logout } from "@/api/auth";

const responseWhiteList = [
  {
    url: "/codeGenerate/downloadCode",
    method: "get",
  },
];

export const useRequestInterceptor = () => {
  const navigate = useNavigate();
  const [done, setDone] = useState(false);
  useEffect(() => {
    request.interceptors.request.use(
      (config) => {
        const token = localStorage.token;
        if (token) config.headers.Authorization = getToken();
        return config;
      },
      (error) => {
        message.error(error instanceof Error ? error.message : "请求失败");
        // 处理请求错误
        return Promise.reject(error);
      }
    );
    request.interceptors.response.use(
      (response) => {
        // prettier-ignore
        const { data, config } = response;
        const { status, message: msg } = data || { status: null, message: "请求失败" };
        const { method, url } = config || {};
        if (status === 401) {
          if (localStorage.token) {
            logout();
            message.error(msg || "请重新登录");
          }
          clearAuthData();
          navigate("/login", { replace: true });
          return Promise.reject(response.data);
        }
        if (responseWhiteList.some((item) => item.method.toLowerCase() === method?.toLocaleLowerCase() && item.url === url)) {
          return Promise.resolve(response.data);
        }
        if (status === 403) {
          message.warning(`{ url: "${url}", method: "${method?.toUpperCase()}" }暂无权限`);
          return Promise.reject(response.data);
        }
        if (status !== 200) {
          message.error(msg || "请求失败");
          return Promise.reject(response.data);
        }
        return Promise.resolve(response.data);
      },
      (error) => {
        if (error?.message === "Network Error") {
          message.error("请检查网络连接");
        } else if (error?.message) {
          message.error(error.message);
        }
        return Promise.reject(error);
      }
    );
    setDone(true);
  }, []);
  return { done };
};

export default useRequestInterceptor;
